


let socket = io();

let app = new Vue({
  el: '#app',
  data: {
    isLogin: true,
    username: '',
    notify: '',
    users: [],
    message: []
  },
  created() {
    let $this = this;
    socket
      .on('connected', () => {
        // console.log('connected');
      })
      .on('user_join', (username, users) => {
        if(username.length > 4) {
          username = username.substring(0, 4) + '…';
        }
        $this.notify = username + ' 进入';
        $this.users = users;
      })
      .on('left', (username) => {
        $this.isLogin = true;
        $this.notify = '';
        $this.username = '';
        $this.users = $this.users.filter(user => user !== username);
      })
      .on('user_left', (username) => {
        if(username.length > 4) {
          username = username.substring(0, 4) + '…';
        }
        $this.notify = username + ' 离开';
        $this.users = $this.users.filter(user => user !== username);
      })
      .on('msg', (data) => {
        $this.message.push(data);
      })

    // 刷新或关闭
    window.onbeforeunload = function(e) {
      // e = e || window.event;
      $this.exit();
    };

  },
  methods: {
    login() {
      let $this = this;
      let el = document.querySelector('.login input');
      let username = el.value.trim();

      if(username.length === 0) {
        toastr.warning('用户名不能为空');
        return;
      }

      if(username.length > 15) {
        toastr.warning('用户名不超过15个字符');
        return;
      }

      socket.emit('check_user', username, function(pass, rs) {
        if(pass) {
          toastr.warning('该用户名已经存在');
          return;
        } else {
          toastr.clear();
          $this.notify = '';
          $this.isLogin = false;
          $this.username = username;
          $this.users = rs;
        }
      });
    },
    exit() {
      socket.emit('user_left', this.username);
    },
    send() {
      let $this = this;
      let el = document.querySelector('textarea');
      let val = el.value.trim();
      if(!val) {
        toastr.warning('消息不能为空');
        return;
      }
      socket.emit('send msg', {
        username: $this.username,
        msg: val
      });
      el.value = '';
    },
  }
});
